
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import render
from django.views import View

from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from apps.payment.utils import alipay
from utils.response_code import RETCODE


class PaymentView(LoginRequiredMixin, View):
    def get(self, request, order_id):
        """获取alipay调用链接"""
        # 1 校验参数 order_id和订单状态
        try:
            order = OrderInfo.objects.get(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"])
        except:
            return HttpResponseForbidden('非法请求! 订单信息错误...')

        # 生成加密url, k=v query_string
        oder_str = alipay.api_alipay_trade_page_pay(
            subject=f"美多mall{order_id}",
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL
        )
        alipay_url = settings.ALIPAY_URL + "?" + oder_str
        # 返回前端链接
        return JsonResponse({"code":RETCODE.OK, "errmsg":'ok', "alipay_url":alipay_url})


# 支付完成 回调路由
class PaymenStatustView(LoginRequiredMixin, View):
    def get(self, request):
        # 获取回调信息
        data_dict = request.GET.dict()  # query_dict是dict子类,支持一键多值,需要转换为标准dict

        # 将回调信息中的signature拆分出来,用以认证
        sign = data_dict.pop('sign')

        # 校验回调信息
        if alipay.verify(data=data_dict, signature=sign):
            # 我们需要将订单编号和交易流水号进行关联存储，方便用户和商家后续使用
            order_id = data_dict.get('out_trade_no')
            trade_no = data_dict.get('trade_no')
            if not Payment.objects.filter(order_id=order_id):
                Payment.objects.create(
                    order_id=order_id,
                    trade_id=trade_no,
                )

            # 付款成功,修改订单状态, 这里改为待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
            context = {
                'trade_no': trade_no,
            }
            return render(request, 'pay_success.html', context)
        else:
            return HttpResponseForbidden('非法请求! 支付信息错误...')
